package com.example.downloader;

import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.IBinder;
import android.util.Log;
import android.app.IntentService;
import java.io.File;
import com.example.Helpers.Timetys;

public class DownloaderIntentService extends IntentService {
	private static final String TAG = "DownloaderIntentService";
	public static final String workingDir = android.os.Environment.getExternalStorageDirectory().getPath() + "/downloader/";

	public DownloaderIntentService() {
		super("DownloaderIntentService");
	}

	protected void onHandleIntent(Intent intent) {
		try {
			SharedPreferences settings = getSharedPreferences("settingPref", 0);
			Log.d(TAG, "trying to download " + settings.getString("testFile", null));
			
			URL url = new URL("http://www.saunalahti.fi/~mikkovma/" + settings.getString("testFile", null));
			URLConnection connection = url.openConnection();
			connection.connect();
			File downloadDir = new File(workingDir);
			downloadDir.mkdirs();
			
			String nowStr = Timetys.getTimeStr();
			
			File outputFile = new File(downloadDir, nowStr + "_testfile");
			InputStream input = new BufferedInputStream(url.openStream());
			OutputStream output = new FileOutputStream(outputFile);

			byte data[] = new byte[1024];

			int count;
			while ((count = input.read(data)) != -1) {
				output.write(data, 0, count);
			}

			output.flush();
			output.close();
			input.close();
			Log.d(TAG, "download succeeded");
		} catch (Exception e) {
			Log.d(TAG, "download failed");
			Log.e(TAG, "exception", e);
		}
		return;
	}

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
}